package com.ruoyi.trade.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.trade.domain.TransactionRecords;
import com.ruoyi.trade.mapper.TransactionRecordsMapper;
import com.ruoyi.trade.service.ITransactionRecordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 成交记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@Service
public class TransactionRecordsServiceImpl implements ITransactionRecordsService
{
    private static final Logger log = LoggerFactory.getLogger(TransactionRecordsServiceImpl.class);

    @Autowired
    private TransactionRecordsMapper transactionRecordsMapper;

    @Autowired
    protected Validator validator;


    /**
     * 查询成交记录
     * 
     * @param id 成交记录主键
     * @return 成交记录
     */
    @Override
    public TransactionRecords selectTransactionRecordsById(Long id)
    {
        return transactionRecordsMapper.selectTransactionRecordsById(id);
    }

    /**
     * 查询成交记录列表
     * 
     * @param transactionRecords 成交记录
     * @return 成交记录
     */
    @Override
    public List<TransactionRecords> selectTransactionRecordsList(TransactionRecords transactionRecords)
    {
        return transactionRecordsMapper.selectTransactionRecordsList(transactionRecords);
    }

    /**
     * 新增成交记录
     * 
     * @param transactionRecords 成交记录
     * @return 结果
     */
    @Override
    public int insertTransactionRecords(TransactionRecords transactionRecords)
    {
        return transactionRecordsMapper.insertTransactionRecords(transactionRecords);
    }

    /**
     * 修改成交记录
     * 
     * @param transactionRecords 成交记录
     * @return 结果
     */
    @Override
    public int updateTransactionRecords(TransactionRecords transactionRecords)
    {
        return transactionRecordsMapper.updateTransactionRecords(transactionRecords);
    }

    /**
     * 批量删除成交记录
     * 
     * @param ids 需要删除的成交记录主键
     * @return 结果
     */
    @Override
    public int deleteTransactionRecordsByIds(Long[] ids)
    {
        return transactionRecordsMapper.deleteTransactionRecordsByIds(ids);
    }

    /**
     * 删除成交记录信息
     * 
     * @param id 成交记录主键
     * @return 结果
     */
    @Override
    public int deleteTransactionRecordsById(Long id)
    {
        return transactionRecordsMapper.deleteTransactionRecordsById(id);
    }

    @Override
    public String importTradeRecords(List<TransactionRecords> tradeList, Boolean isUpdateSupport) {

        if (StringUtils.isNull(tradeList) || tradeList.size() == 0)
        {
            throw new ServiceException("导入交易记录数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TransactionRecords trade : tradeList)
        {
            try
            {
                // 验证是否存在这个合同编号的记录
                TransactionRecords t = transactionRecordsMapper.selectTransactionRecordsByNumber(trade.getContractNumber());
                //不存在则插入
                if (StringUtils.isNull(t))
                {
                    BeanValidators.validateWithException(validator, trade);
                    transactionRecordsMapper.insertTransactionRecords(trade);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、合同编号 " + trade.getContractNumber() + " 导入成功");
                }
//                else if (isUpdateSupport)
                else
                {
                    BeanValidators.validateWithException(validator, trade);
                    trade.setId(t.getId());
                    transactionRecordsMapper.updateTransactionRecords(trade);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、合同编号 " + trade.getContractNumber() + " 更新成功");
                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、合同编号 " + trade.getContractNumber() + " 已存在");
//                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、合同编号 " + trade.getContractNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Transactional
    @Override
    public int assignClearGroup(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("未选择任何记录");
        }

        // 1. 获取所有选中记录
        List<TransactionRecords> records = transactionRecordsMapper.selectTradeListByIds(ids);
        if (records.size() != ids.size()) {
            throw new ServiceException("部分记录不存在或已被删除");
        }

        // 2. 检查所有选中记录是否有相同的编号或都为空
        Set<Long> existingGroupNumbers = new HashSet<>();
        for (TransactionRecords record : records) {
            if (record.getClearGroupNumber() != null) {
                existingGroupNumbers.add(record.getClearGroupNumber());
            }
        }

        // 3. 如果存在多个不同的编号（排除null）
//        if (existingGroupNumbers.size() > 1) {
//            throw new ServiceException("选中的记录中包含多个不同的清算组编号");
//        }

        // 4. 对于每个非空清算组，检查是否所有记录都被选中
        for (Long groupNumber : existingGroupNumbers) {
            // 获取该清算组的所有记录
            List<TransactionRecords> sameGroupRecords = transactionRecordsMapper.selectTradeListByClearNumber(groupNumber);

            // 获取该组所有记录的ID
            Set<Long> sameGroupIds = sameGroupRecords.stream()
                    .map(TransactionRecords::getId)
                    .collect(Collectors.toSet());

            // 检查是否所有记录都被选中
            if (!ids.containsAll(sameGroupIds)) {
                throw new ServiceException("存在未选中的相同编号记录，请确保选中所有编号为 " + groupNumber + " 的记录");
            }
        }

        // 5. 获取新的清算组编号（当前最大值+1）
        Long newGroupNumber = getNextGroupNumber();

        // 6. 更新所有选中记录
        return transactionRecordsMapper.updateClearGroupNumberByIds(newGroupNumber,ids);
    }

    @Transactional
    @Override
    public int clearGroupNumber(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("未选择任何记录");
        }

        // 1. 获取所有选中记录
        List<TransactionRecords> records = transactionRecordsMapper.selectTradeListByIds(ids);
        if (records.size() != ids.size()) {
            throw new ServiceException("部分记录不存在或已被删除");
        }

        Set<Long> groupNumbers = records.stream()
                .map(TransactionRecords::getClearGroupNumber)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 2. 校验是否选中了带有编号的记录
        if (groupNumbers.isEmpty()) {
            throw new ServiceException("选中的记录均未设置清算组编号");
        }

        // 3. 对于每个非空清算组，检查是否所有记录都被选中
        for (Long groupNumber : groupNumbers) {
            // 获取该清算组的所有记录
            List<TransactionRecords> sameGroupRecords = transactionRecordsMapper.selectTradeListByClearNumber(groupNumber);

            // 获取该组所有记录的ID
            Set<Long> sameGroupIds = sameGroupRecords.stream()
                    .map(TransactionRecords::getId)
                    .collect(Collectors.toSet());

            // 检查是否所有记录都被选中
            if (!ids.containsAll(sameGroupIds)) {
                throw new ServiceException("存在未选中的相同编号记录，请确保选中所有编号为 " + groupNumber + " 的记录");
            }
        }

        // 4. 执行清除操作
        return transactionRecordsMapper.clearGroupNumberByIds(ids);
    }

    // 获取下一个可用的清算组编号
    private Long getNextGroupNumber() {
        // 查询当前最大编号
        Long maxClearNumber = transactionRecordsMapper.selectMaxClearNumber();

        // 如果没有记录，从1开始
        if (maxClearNumber == null) {
            return 1L;
        }

        // 返回最大编号+1
        return maxClearNumber + 1;
    }
}
